package com.hanson.api;

import com.alibaba.fastjson.JSONObject;
import com.hanson.common.bean.ResultMessage;
import com.hanson.common.util.BusinessUtil;
import com.hanson.entity.CartBean;
import com.hanson.service.CartService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Slf4j
@Api(tags = "购物车管理")
@RestController
@RequestMapping("/api/cart")
public class CartApiController {
    @Autowired
    private CartService cartService;

    @ApiOperation(value = "添加商品到购物车")
    @RequestMapping(value = "add", method = RequestMethod.POST)
    public ResultMessage add(@RequestBody CartBean cartBean, HttpServletRequest request) {
        String openId = BusinessUtil.getHeaderOpenId(request);
        cartService.addCart(openId, cartBean);
        ResultMessage resultMessage = new ResultMessage();
        resultMessage.setMsg("加入购物车成功！");
        return resultMessage;
    }

    @ApiOperation(value = "删除购物车商品")
    @RequestMapping(value = "delete", method = RequestMethod.POST)
    public ResultMessage delete(@RequestBody String[] ids, HttpServletRequest request) {
        cartService.deleteCart(ids);
        ResultMessage resultMessage = new ResultMessage();
        resultMessage.setMsg("删除购物车商品成功！");
        return resultMessage;
    }

    @ApiOperation(value = "修改购物车商品")
    @RequestMapping(value = "/update", method = RequestMethod.POST)
    public ResultMessage update(@RequestBody CartBean cartBean, HttpServletRequest request) throws Exception {
        String openId = BusinessUtil.getHeaderOpenId(request);
        cartService.updateCart(openId, cartBean);
        ResultMessage resultMessage = new ResultMessage();
        resultMessage.setMsg("修改成功！");
        return resultMessage;
    }

    @ApiOperation(value = "查询用户购物车列表")
    @RequestMapping(value = "/cartList", method = RequestMethod.GET)
    public ResultMessage cartList(HttpServletRequest request) throws Exception {
        String openId = BusinessUtil.getHeaderOpenId(request);
        ModelMap modelMap = new ModelMap();
        List<CartBean> cartBeanList = cartService.selectByOpenId(openId, modelMap);
        ResultMessage resultMessage = new ResultMessage();
        resultMessage.setMsg("修改成功！");
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("totalCount", modelMap.get("totalCount"));
        jsonObject.put("totalPrice", modelMap.get("totalPrice"));
        jsonObject.put("data", cartBeanList);
        resultMessage.setData(jsonObject);
        return resultMessage;
    }
}
